package com.zxe.categoryserver.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zxe.categoryserver.mapper.CategoryMapper;
import com.zxe.categoryserver.pojo.Category;
import com.zxe.categoryserver.pojo.CategoryDTO;
import com.zxe.categoryserver.pojo.CategoryPageQueryDTO;
import com.zxe.categoryserver.service.CategoryService;
import com.zxe.commonserver.constant.MessageConstant;
import com.zxe.commonserver.exception.DeletionNotAllowedException;
import com.zxe.commonserver.result.PageResult;
import com.zxe.feignapi.clients.FreshClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private FreshClient freshClient;

    /**
     * 新增分类
     * @param categoryDTO
     */
    public void save(CategoryDTO categoryDTO) {
        Category category = new Category();
        BeanUtils.copyProperties(categoryDTO, category);
        category.setStatus(0);
        categoryMapper.insert(category);
    }

    /**
     * 分类分页查询
     * @param categoryPageQueryDTO
     * @return
     */
    public PageResult page(CategoryPageQueryDTO categoryPageQueryDTO) {
        PageHelper.startPage(categoryPageQueryDTO.getPage(), categoryPageQueryDTO.getPageSize());
        //下一条sql进行分页，自动加入limit关键字分页
        Page<Category> page = categoryMapper.page(categoryPageQueryDTO);
        long total = page.getTotal();
        List<Category> categories = page.getResult();
        return new PageResult(total, categories);
    }

    /**
     * 删除分类
     * @param id
     */
    public void delete(Long id) {
        Integer count = freshClient.countByCategoryId(id);
        if (count > 0) {
            //当前分类关联了生鲜，不能删除
            throw new DeletionNotAllowedException(MessageConstant.CATEGORY_BE_RELATED_BY_FRESH);
        }
        categoryMapper.delete(id);
    }

    /**
     * 修改分类
     * @param categoryDTO
     */
    public void update(CategoryDTO categoryDTO) {
        Category category = new Category();
        BeanUtils.copyProperties(categoryDTO, category);
        categoryMapper.update(category);
    }

    /**
     * 启用、禁用分类
     * @param status
     * @param id
     */
    public void startOrStop(Integer status, Long id) {
        Category category = Category.builder()
                .id(id)
                .status(status)
                .build();
        categoryMapper.update(category);
    }

    /**
     * 查询全部分类
     * @return
     */
    public List<Category> list() {
        return categoryMapper.list();
    }
}
